/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.bingoogolapple.bgabanner.demo.provider;

import cn.bingoogolapple.bgabanner.demo.ResourceTable;
import cn.bingoogolapple.bgabanner.demo.model.RefreshModel;
import cn.bingoogolapple.bgabanner.utils.DensityUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;

import java.util.ArrayList;
import java.util.List;

public class ListViewProvider extends BaseItemProvider {
    List<RefreshModel> listdata;
    AbilitySlice abilitySlice;
    private Component parse;
    private int num;
    private int count = 2;

    /**
     * constructor
     *
     * @param listdata
     * @param abilitySlice
     * @param num
     */
    public ListViewProvider(List<RefreshModel> listdata, AbilitySlice abilitySlice, int num) {
        if (listdata == null) {
            this.listdata = new ArrayList<>();
        } else {
            this.listdata = listdata;
        }
        this.abilitySlice = abilitySlice;
        this.num = num;
    }

    @Override
    public int getCount() {
        if (listdata == null) {
            return 0;
        }
        return listdata.size();
    }

    @Override
    public Object getItem(int i) {
        if (listdata == null) {
            return null;
        }
        return listdata.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        if (component == null) {
            parse = LayoutScatter.getInstance(abilitySlice).parse(ResourceTable.Layout_item_list, null, false);
        } else {
            parse = component;
        }
        if (listdata == null) {
            this.listdata = new ArrayList<>();
        }
        RefreshModel listdata = this.listdata.get(position);
        Text tv_one = (Text) parse.findComponentById(ResourceTable.Id_tv_one);
        Text tv_two = (Text) parse.findComponentById(ResourceTable.Id_tv_two);
        DirectionalLayout lyout = (DirectionalLayout) parse.findComponentById(ResourceTable.Id_item);
        tv_one.setText(listdata.title);
        tv_two.setText(listdata.detail);
        if (num == count) {
            lyout.setWidth(DensityUtils.getDeviceAttr(componentContainer.getContext()).getAttributes().width / 2);
        }
        return parse;
    }
}
